<template>
  <div class="coach-admin">
    <h3 class="section-title">教练管理</h3>

    <!-- ① 待审核教练（仅显示待审核） -->
    <h4 class="sub-title">待审核</h4>
    <el-table :data="pendingCoaches" style="width: 100%">
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="real_name" label="真实姓名" />
      <el-table-column prop="phone" label="手机号" />
      <el-table-column prop="gender" label="性别" />
      <el-table-column prop="age" label="年龄" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="teaching_years" label="教龄" />
      <el-table-column prop="teaching_experience" label="教学经历" />
      <el-table-column label="证件照">
        <template #default="scope">
          <img v-if="scope.row.photo" :src="scope.row.photo" class="avatar-sm" />
          <span v-else>无</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="260">
        <template #default="scope">
          <el-button size="small" type="success" @click="approveCoach(scope.row)">通过</el-button>
          <el-button size="small" type="danger" @click="rejectCoach(scope.row.id)">拒绝</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- ② 已审核教练（显示全部字段） -->
    <h4 class="sub-title">已审核</h4>
    <el-table :data="approvedCoaches" style="width: 100%">
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="real_name" label="真实姓名" />
      <el-table-column prop="phone" label="手机号" />
      <el-table-column prop="gender" label="性别" />
      <el-table-column prop="age" label="年龄" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="level" label="等级">
        <template #default="scope">
          <el-tag :type="levelColor(scope.row.level)">{{ scope.row.level }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="teaching_years" label="教龄" />
      <el-table-column prop="teaching_experience" label="教学经历" />
      <el-table-column label="证件照">
        <template #default="scope">
          <img v-if="scope.row.photo" :src="scope.row.photo" class="avatar-sm" />
          <span v-else>无</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="editCoach(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteCoach(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增按钮 -->
    <el-button type="primary" class="mt-16" @click="addCoach">新增教练</el-button>

    <!-- 共用对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle">
      <el-form :model="form" label-width="100px">
        <el-form-item label="用户名"><el-input v-model="form.username" /></el-form-item>
        <el-form-item label="真实姓名"><el-input v-model="form.real_name" /></el-form-item>
        <el-form-item label="手机号"><el-input v-model="form.phone" /></el-form-item>
        <el-form-item label="性别">
          <el-select v-model="form.gender">
            <el-option label="男" value="male" />
            <el-option label="女" value="female" />
          </el-select>
        </el-form-item>
        <el-form-item label="年龄"><el-input-number v-model="form.age" :min="1" :max="120" /></el-form-item>
        <el-form-item label="邮箱"><el-input v-model="form.email" /></el-form-item>
        <el-form-item label="教练等级">
          <el-select v-model="form.level">
            <el-option label="高级" value="senior" />
            <el-option label="中级" value="intermediate" />
            <el-option label="初级" value="junior" />
          </el-select>
        </el-form-item>
        <el-form-item label="教龄"><el-input-number v-model="form.teaching_years" :min="0" :max="100" /></el-form-item>
        <el-form-item label="教学经历"><el-input v-model="form.teaching_experience" type="textarea" :rows="3" /></el-form-item>
        <el-form-item label="证件照">
          <el-upload
              class="avatar-uploader"
              action="https://jsonplaceholder.typicode.com/posts/"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.photo" :src="form.photo" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="管理校区">
          <el-select v-model="form.campus_id" placeholder="请选择校区">
            <el-option v-for="c in campusOptions" :key="c.id" :label="c.name" :value="c.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveCoach">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import { useAuthStore } from '@/stores/auth'
import { Plus } from '@element-plus/icons-vue'

const authStore = useAuthStore()
const user = computed(() => authStore.user)              // 当前登录管理员（用于校区过滤）

const students = ref([])              // 全部学员
const pendingCoaches = ref([])        // 待审核
const approvedCoaches = ref([])       // 已审核
const campusOptions = ref([])         // 校区下拉

const dialogVisible = ref(false)
const dialogTitle = computed(() => (currentId.value ? '编辑教练' : '新增教练'))
const currentId = ref(null)

const form = ref({
  username: '',
  real_name: '',
  phone: '',
  gender: 'male',
  age: 25,
  email: '',
  level: 'junior',
  teaching_years: 0,
  teaching_experience: '',
  photo: '',
  campus_id: ''
})

/* ---------- 生命周期 ---------- */
onMounted(() => {
  fetchCoaches()
  fetchCampusOptions()
})

/* ---------- 数据获取 ---------- */
const fetchCoaches = async () => {
  const res = await request.get('/coach/list-with-campus') // 返回含 campus_name
  if (res.code === 200) {
    const data = res.data
    // 超级管理员看全部，普通管理员只看自己校区
    const filtered = user.value.isSuperAdmin
        ? data
        : data.filter(c => c.campus_id === user.value.campus.id)

    pendingCoaches.value = filtered.filter(c => c.status === 0)
    approvedCoaches.value = filtered.filter(c => c.status === 1)
  }
}

const fetchCampusOptions = async () => {
  const res = await request.get('/campus/options')
  if (res.code === 200) campusOptions.value = res.data
}

/* ---------- 增删改 ---------- */
const addCoach = () => {
  currentId.value = null
  form.value = {
    username: '',
    real_name: '',
    phone: '',
    gender: 'male',
    age: 25,
    email: '',
    level: 'junior',
    teaching_years: 0,
    teaching_experience: '',
    photo: '',
    campus_id: ''
  }
  dialogVisible.value = true
}

const editCoach = (row) => {
  currentId.value = row.id
  form.value = { ...row }
  dialogVisible.value = true
}

const saveCoach = async () => {
  if (currentId.value) {
    await request.put(`/coach/update/${currentId.value}`, form.value)
    ElMessage.success('教练信息更新成功')
  } else {
    await request.post('/coach/add', form.value)
    ElMessage.success('教练添加成功')
  }
  dialogVisible.value = false
  await fetchCoaches()
}

const deleteCoach = async (id) => {
  await ElMessageBox.confirm('确定删除该教练？', '提示', { type: 'warning' })
  await request.delete(`/coach/delete/${id}`)
  ElMessage.success('教练删除成功')
  await fetchCoaches()
}

/* ---------- 审核 ---------- */
const approveCoach = async (row) => {
  await request.put(`/coach/approve/${row.id}`, { level: 'junior' }) // 默认初级，可弹窗选等级
  ElMessage.success('审核通过')
  await fetchCoaches()
}

const rejectCoach = async (id) => {
  await request.delete(`/coach/reject/${id}`)
  ElMessage.success('已拒绝并删除')
  await fetchCoaches()
}

/* ---------- 工具 ---------- */
const levelColor = (level) => {
  const map = { senior: 'danger', intermediate: 'warning', junior: '' }
  return map[level] || ''
}

const handleAvatarSuccess = (res, file) => {
  form.value.photo = URL.createObjectURL(file.raw)
}

const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isJPG && !isPNG) ElMessage.error('仅支持 JPG/PNG')
  if (!isLt2M) ElMessage.error('大小不超过 2MB')
  return (isJPG || isPNG) && isLt2M
}
</script>

<style scoped>
.coach-admin {
  padding: 24px;
}
.section-title {
  margin: 24px 0 12px;
  font-size: 18px;
  color: var(--el-color-primary);
}
.sub-title {
  margin: 16px 0 8px;
  font-size: 16px;
  color: var(--el-text-color-regular);
}
.mt-16 {
  margin-top: 16px;
}
.avatar-sm {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  object-fit: cover;
}
.avatar {
  width: 120px;
  height: 120px;
  border-radius: 4px;
  object-fit: cover;
}
.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 4px;
  cursor: pointer;
  overflow: hidden;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
</style>